package com.iltgcl.echovoicedemo.speaker

import android.media.AudioManager
import androidx.media.AudioAttributesCompat
import androidx.media.AudioFocusRequestCompat
import androidx.media.AudioManagerCompat
import com.iltgcl.echovoice.client.IEchoVoice
import com.iltgcl.echovoicedemo.speaker.IEchoSpeaker.Companion.AUDIO_FOCUS_LOSS_TRANSIENT_POLICY_VOLUME_DOWN
import timber.log.Timber

/**
 * 用于小说阅读或新闻类应用，音频策略如下：
 * 1 长时间丢失焦点（例如音乐应用请求焦点成功后）则停止播放
 * 2 短暂丢失焦点（例如读屏/导航等应用请求焦点成功后）
 *   2.1 默认则暂停播放，重新获得焦点则继续播放
 *   2.2 若设置 AUDIO_FOCUS_LOSS_TRANSIENT_POLICY_VOLUME_DOWN，则媒体降低音量与读屏/导航混音
 */
class MediaSpeaker(
    audioManager: AudioManager,
    echoVoice: IEchoVoice,
    lossTransientPolicy:Int) : EchoSpeakerBase(audioManager, echoVoice, IEchoVoice.USAGE_MEDIA) {

    override var focusLossTransientPolicy = lossTransientPolicy

    private val focusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange ->
        Timber.d("[onAudioFocusChange]$usage, $focusChange")
        when (focusChange) {
            //长时间丢失焦点,当其他应用申请的焦点为AUDIOFOCUS_GAIN时触发此回调
            AudioManager.AUDIOFOCUS_LOSS -> {
                Timber.d("---------------- AUDIOFOCUS_LOSS ")
                stop()
            }
            //短暂性丢失焦点，当其他应用申请AUDIOFOCUS_GAIN_TRANSIENT或AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE时触发
            AudioManager.AUDIOFOCUS_LOSS_TRANSIENT, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
                when(focusLossTransientPolicy) {
                    AUDIO_FOCUS_LOSS_TRANSIENT_POLICY_VOLUME_DOWN -> {
                        Timber.d("---------------- volumeDown ")
                        volumeDown()
                    }
                    else -> {
                        Timber.d("---------------- pause ")
                        pause(false)
                    }
                }
            }
            //当其他应用申请焦点之后又释放焦点会触发此回调
            AudioManager.AUDIOFOCUS_GAIN -> {
                Timber.d("---------------- AUDIOFOCUS_GAIN ")
                when(focusLossTransientPolicy) {
                    AUDIO_FOCUS_LOSS_TRANSIENT_POLICY_VOLUME_DOWN -> {
                        Timber.d("---------------- volumeRestore ")
                        volumeRestore()
                    }
                    else -> {
                        Timber.d("---------------- resume ")
                        resume()
                    }
                }
            }
        }
    }
    private val focusRequest = AudioFocusRequestCompat.Builder(AudioManagerCompat.AUDIOFOCUS_GAIN)
        .setAudioAttributes(
            AudioAttributesCompat.Builder()
                .setContentType(AudioAttributesCompat.CONTENT_TYPE_MUSIC)
                .setUsage(AudioAttributesCompat.USAGE_MEDIA)
                .build())
        .setWillPauseWhenDucked(true)
        .setOnAudioFocusChangeListener(focusChangeListener)
        .build()

    override fun requestAudioFocus(audioManager: AudioManager):Int {
        return AudioManagerCompat.requestAudioFocus(audioManager, focusRequest)
    }

    override fun abandonAudioFocus(audioManager: AudioManager): Int {
        return AudioManagerCompat.abandonAudioFocusRequest(audioManager, focusRequest)
    }
}
